package 栈;

import java.util.Stack;

/**
 * @author 陈艺博
 * @date 2021-02-20 21:52
 * @description https://leetcode-cn.com/problems/basic-calculator/
 **/
public class _224_basic_calculator_基本计算器 {
    public static void main(String[] args) {
        calculate("1 + (10*2)");
    }
    static int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        // 正负号
        int sign = 1;
        // 结果
        int res = 0;
        // 长度
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char ch = s.charAt(i);
            //判断是否是数字
            if (Character.isDigit(ch)) {
                int cur = ch - '0';
                while (i + 1 < length && Character.isDigit(s.charAt(i + 1))) {
                    cur = cur * 10 + s.charAt(++i) - '0';
                }
                res = res + sign * cur;
            } else if (ch == '+') {
                sign = 1;
            } else if (ch == '-') {
                sign = -1;
            } else if (ch == '(') {
                stack.push(res);
                res = 0;
                stack.push(sign);
                sign = 1;
            } else if (ch == ')') {
                res = stack.pop() * res + stack.pop();
            }
        }
        return res;
    }
}
